package com.aaa.tars.service.impl;

import com.aaa.tars.dao.RefundDao;
import com.aaa.tars.entity.Order;
import com.aaa.tars.entity.Refund;
import com.aaa.tars.service.OrderService;
import com.aaa.tars.service.RefundService;
import com.aaa.tars.util.CustomException;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @FileName: RefundServiceImpl
 * @Description:
 * @Author: ghz
 * @CreateTime:2025/9/12 14:11
 * @Version:1.0.0
 */
@Service
public class RefundServiceImpl implements RefundService {
    @Resource
    private RefundDao refundDao;
    
    @Resource
    private OrderService orderService;

    @Override
    public Refund queryById(Integer refundId) {
        if (refundId == null || refundId <= 0){
            throw new CustomException(ResultStatus.ERROR.getStatusCode(),ResultStatus.ERROR.getStatusMessage());
        }
        return refundDao.queryById(refundId);
    }

    @Override
    public PageInfo queryByPage(Page<Refund> page) {
        Integer pageSize = page.getPageSize();
        Integer pageNo = page.getPageNo();
        if (pageNo == null || pageNo <= 0 || pageSize == null || pageSize <= 0) {
            throw new CustomException(ResultStatus.ERROR.getStatusCode(),
                    ResultStatus.ERROR.getStatusMessage());
        }
        PageHelper.startPage(pageNo, pageSize);
        Refund data = page.getData();
        return new PageInfo(refundDao.queryByParam( data));
    }

    @Override
    public int insert(Refund refund) {
        // 1. 参数校验
        if (refund.getOrderNo() == null || refund.getOrderNo().trim().isEmpty()) {
            throw new CustomException(400, "订单号不能为空");
        }
        
        if (refund.getRefundIje() == null || refund.getRefundIje() <= 0) {
            throw new CustomException(400, "退款金额必须大于0");
        }
        
        // 2. 校验订单状态（新增）
        // 检查订单是否已取票，已取票的订单不能退款
        Order order = orderService.queryByNo(refund.getOrderNo());
        if (order == null) {
            throw new CustomException(400, "订单不存在");
        }
        
        // 如果订单状态为"已取票"，则不允许退款
        if ("13".equals(order.getOrderState())) {
            throw new CustomException(400, "已取票的订单不能申请退款");
        }
        
        // 3. 强制生成refund_serialno（后端兜底，确保非空）
        String refundSerialno = generateRefundSerialno();
        refund.setRefundSerialno(refundSerialno); // 覆盖前端传递的值（若有）

        // 4. 设置退款时间（原有逻辑保留）
        refund.setRefundTime(new Date());

        // 5. 补充：默认设置退款结果为"0-处理中"（避免其他字段空值）
        if (refund.getRefundResult() == null || refund.getRefundResult().trim().isEmpty()) {
            refund.setRefundResult("0"); // 0-处理中，1-成功，2-失败
        }
        if (refund.getRefundRespcode() == null || refund.getRefundRespcode().trim().isEmpty()) {
            refund.setRefundRespcode("REFUND_INIT"); // 初始响应码
        }
        
        // 6. 如果没有填写退款原因，则设置默认值
        if (refund.getRefundFullmsg() == null || refund.getRefundFullmsg().trim().isEmpty()) {
            refund.setRefundFullmsg("用户申请退款");
        }

        // 7. 插入数据库
        return refundDao.insert(refund);
    }

    // 新增：生成唯一退款流水号（规则：REF + 年月日时分秒 + 3位随机数）
    private String generateRefundSerialno() {
        // 1. 格式化当前时间（yyyyMMddHHmmss，如20250920153045）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(new Date());

        // 2. 生成3位随机数（000-999，补0确保3位）
        String random = String.format("%03d", new Random().nextInt(1000));

        // 3. 拼接流水号（如REF20250920153045123）
        return "REF" + dateStr + random;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Refund refund) {
        // 更新前校验refundId
        if (refund.getRefundId() == null || refund.getRefundId() <= 0) {
            throw new CustomException(400, "退款记录ID无效");
        }

        // 记录更新日志
        System.out.println("更新退款记录: refundId=" + refund.getRefundId() +
                ", refundResult=" + refund.getRefundResult() +
                ", refundRespcode=" + refund.getRefundRespcode() +
                ", refundFullmsg=" + refund.getRefundFullmsg());

        // 查询现有记录，确保不会意外覆盖其他字段
        Refund existingRefund = refundDao.queryById(refund.getRefundId());
        if (existingRefund == null) {
            throw new CustomException(400, "退款记录不存在");
        }

        // 打印更新前后的对比
        System.out.println("更新前: refundResult=" + existingRefund.getRefundResult() +
                ", refundRespcode=" + existingRefund.getRefundRespcode());
        System.out.println("更新后: refundResult=" + refund.getRefundResult() +
                ", refundRespcode=" + refund.getRefundRespcode());

        int result = refundDao.update(refund);

        if (result > 0) {
            System.out.println("退款记录更新成功");

            // 验证更新结果
            Refund updatedRefund = refundDao.queryById(refund.getRefundId());
            System.out.println("验证更新结果: refundResult=" + updatedRefund.getRefundResult() +
                    ", refundRespcode=" + updatedRefund.getRefundRespcode());
        } else {
            System.out.println("退款记录更新失败，可能记录不存在或数据未变化");
        }

        return result;
    }

    @Override
    public int deleteById(Integer refundId) {
        if (refundId== null|| refundId<=0){
            throw  new CustomException(ResultStatus.ERROR.getStatusCode(),ResultStatus.ERROR.getStatusMessage());
        }
        return this.refundDao.deleteById(refundId);
    }
    
    /**
     * 根据订单号查询退款记录
     * @param orderNo 订单号
     * @return 退款记录列表
     */
    public List<Refund> queryByOrderNo(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            throw new CustomException(400, "订单号不能为空");
        }
        
        Refund queryParam = new Refund();
        queryParam.setOrderNo(orderNo);
        return refundDao.queryByParam(queryParam);
    }
}